import userApi from '@/pages/Organization/UserManagement/request';
import { DrawerForm, ProForm, ProFormText } from '@ant-design/pro-components';
import { Button, Form } from 'antd';
import { useMemo, useState } from 'react';

export type Data = UserManagementApi.InfoResponse;
export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  data?: UserManagementApi.ListResponse;
  onSuccess?: () => void;
  onCancel?: () => void;
}
const colSpan = 2;
function UserManagementPasswordForm(props: Props) {
  const { data } = props;
  const [form] = Form.useForm<Data>();

  const [info, setInfo] = useState<Partial<UserManagementApi.InfoResponse>>({});

  const getInfo = async (params: UserManagementApi.InfoParams) => {
    const userInfo = await userApi.getInfo(params);
    const { roleDepartmentLists } = userInfo;
    if (roleDepartmentLists && roleDepartmentLists.length) {
      const roleDepartment = roleDepartmentLists[0];
      const { groupID, subsidiaryID, departmentId, userRoleId } = roleDepartment;
      Object.assign(userInfo, { groupID, subsidiaryID, departmentId, userRoleId });
    }
    form.setFieldsValue(userInfo);
    setInfo(userInfo);
  };

  const onSubmit = async (form: any) => {
    const params: UserManagementApi.PasswordParams = {
      mobileno: info.mobileno || '',
      password: form.password || null,
    };
    const data = await userApi.updatePassword(params);
    if (data.success) props.onSuccess?.();
    return data.success;
  };
  const onOpenChange = (open: boolean) => {
    if (open) {
      if (!!data && !!data.id) {
        getInfo({ id: data.id });
      }
    } else {
      form.resetFields();
      props.onCancel?.();
    }
  };

  const formConfig = useMemo(() => {
    const password = {
      Component: ProFormText.Password,
      props: {
        name: 'password',
        rules: [{ required: true }],
        width: 'md',
        label: '密码',
        placeholder: '请输入密码',
      },
    };

    const form: {
      [key in string]: FormConfig;
    } = {
      password,
    };
    return form;
  }, []);
  const drawerFormData = useMemo(() => {
    const data: FormConfig[][] = [];
    const keys = Object.keys(formConfig);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      const index = Math.floor(i / colSpan);
      if (!data[index]) data[index] = [];
      data[index].push(formConfig[key]);
    }
    return data;
  }, [formConfig]);

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`更改密码`}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
        onResize() {},
      }}
      trigger={<Button type="link">更改密码</Button>}
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      {drawerFormData.map((item, i) => {
        return (
          <ProForm.Group key={i}>
            {item.map((data) => {
              const { props, Component } = data;
              return <Component key={props.name} {...props} />;
            })}
          </ProForm.Group>
        );
      })}
    </DrawerForm>
  );
}

export default UserManagementPasswordForm;
